﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeManageService;

namespace WeManageForm.Wish
{
	public partial class WishForm : Form
	{
		private int function;
		private WeManageService.Wish wish;

		public WishForm()
		{
			InitializeComponent();
			TxtDescription.GotFocus += Global.EmptyHintTextBox_GotFocus;
			TxtDescription.LostFocus += Global.EmptyHintTextBox_LostFocus;
			wish = new WeManageService.Wish();
			function = 0;
			btnFinish.Visible = false;
			TxtDescription.TextChanged += DisableFinishBtn;
			TxtScore.TextChanged += DisableFinishBtn;
			TxtTitle.TextChanged += DisableFinishBtn;
		}

		public WishForm(WeManageService.Wish wish)
		{
			InitializeComponent();
			TxtDescription.GotFocus += Global.EmptyHintTextBox_GotFocus;
			TxtDescription.LostFocus += Global.EmptyHintTextBox_LostFocus;
			this.wish = wish;
			function = 1;
			TxtTitle.Text = wish.Name;
			TxtScore.Text = wish.RequiredScore.ToString();
			Global.SetEmptyHintTextBoxValue(TxtDescription, wish.Details);
			TxtDescription.TextChanged += DisableFinishBtn;
			TxtScore.TextChanged += DisableFinishBtn;
			TxtTitle.TextChanged += DisableFinishBtn;
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void btnConfirm_Click(object sender, EventArgs e)
		{
			try
			{
				if (TxtTitle.Text == "")
				{
					lblAlert.Text = "错误！标题不能为空！";
				}
				else if (int.TryParse(TxtScore.Text, out int score) && score > 0)
				{
					wish.Name = TxtTitle.Text;
					wish.RequiredScore = score;
					wish.Details = Global.GetEmptyHintTextBoxValue(TxtDescription);
					wish.UserName = Global.UserName;
					if (function == 0) WishManager.AddWish(wish);
					else WishManager.ModifyWish(wish);
					this.Close();
				}
				else
				{
					lblAlert.Text = "错误！分数必须是大于0的整数！";
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnFinish_Click(object sender, EventArgs e)
		{
			if (int.TryParse(TxtScore.Text, out int score) && score > 0)
			{
				wish.RequiredScore = score;
			}
			if (WishManager.FinishWish(wish.WishID))
			{
				MessageBox.Show("愿望已完成！");
				this.Close();
			}
			else
			{
				MessageBox.Show("积分不足，完成失败", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}

		private void DisableFinishBtn(object sender, EventArgs e)
		{
			btnFinish.Enabled = false;
		}
	}
}
